#import "FlutterAlarmPlugin.h"
#import <UserNotifications/UserNotifications.h>
#import "DBManager.h"

@interface FlutterAlarmPlugin () <UNUserNotificationCenterDelegate>

@end

@implementation FlutterAlarmPlugin

#pragma mark - Helpers

- (UNNotificationSound *)alarmSoundForCurrentBundle API_AVAILABLE(ios(10.0)) {
    NSArray<NSString *> *candidates = @[@"alarm.caf", @"alarm.wav", @"alarm.aiff"];
    for (NSString *fileName in candidates) {
        NSString *resourceName = [fileName stringByDeletingPathExtension];
        NSString *extension = [fileName pathExtension];
        if ([[NSBundle mainBundle] URLForResource:resourceName withExtension:extension]) {
            return [UNNotificationSound soundNamed:fileName];
        }
    }
    return [UNNotificationSound defaultSound];
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_alarm"
            binaryMessenger:[registrar messenger]];
  FlutterAlarmPlugin* instance = [[FlutterAlarmPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 设置通知代理
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
        } else {
            // Fallback on earlier versions
        }
    }
    return self;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS" stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"checkPermission" isEqualToString:call.method]) {
    [self checkPermission:result];
  } else if ([@"requestPermission" isEqualToString:call.method]) {
    [self requestPermission:result];
  } else if ([@"setAlarm" isEqualToString:call.method]) {
    [self setAlarm:call.arguments result:result];
  } else if ([@"setRepeatingAlarm" isEqualToString:call.method]) {
    [self setRepeatingAlarm:call.arguments result:result];
  } else if ([@"cancelAlarm" isEqualToString:call.method]) {
    [self cancelAlarm:call.arguments result:result];
  } else if ([@"cancelAllAlarms" isEqualToString:call.method]) {
      [self cancelAllAlarms:call.arguments result:result];
  }else if ([@"cancelAlarmsByTag" isEqualToString:call.method]) {
      [self cancelAlarmsByTag:call.arguments result:result];
  }else if ([@"getAllAlarms" isEqualToString:call.method]) {
      [self getAllAlarms:call.arguments result:result];
  }else if ([@"getAlarmsByTag" isEqualToString:call.method]) {
      [self getAlarmsByTag:call.arguments result:result];
  }else if ([@"getAlarmByAlarmId" isEqualToString:call.method]) {
      [self getAlarmByalarmId:call.arguments result:result];
  }else if ([@"settingPermission" isEqualToString:call.method]) {
    [self jumpToSettings:result];
  } else {
    result(FlutterMethodNotImplemented);
  }
    
}

- (void)checkPermission:(FlutterResult)result {
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            dispatch_async(dispatch_get_main_queue(), ^{
                BOOL granted = (settings.authorizationStatus == UNAuthorizationStatusAuthorized);
                result(@(granted));
            });
        }];
    } else {
        // Fallback on earlier versions
    }
}

- (void)requestPermission:(FlutterResult)result {
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{

                if(!granted){
                    [self jumpToSettings:result];
                }

                result(@(granted));
            });
        }];
    } else {
        // Fallback on earlier versions
    }
}

- (void)jumpToSettings:(FlutterResult)result {
    
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                if (success) {
                    NSLog(@"跳转到设置成功");
                } else {
                    NSLog(@"跳转到设置失败");
                }
            }];
        } else {
            // Fallback on earlier versions
        }
    }
}

- (void)setAlarm:(NSDictionary*)arguments result:(FlutterResult)result {

    NSString *tag = [NSString stringWithFormat: @"%@", arguments[@"tag"]];
    NSString *alarm_id = [NSString stringWithFormat: @"%@", arguments[@"alarm_id"]];
    NSString *date = [NSString stringWithFormat: @"%@", arguments[@"date"]];
    NSNumber *hour = arguments[@"hour"];
    NSNumber *minute = arguments[@"minute"];
    NSString *title = [NSString stringWithFormat: @"%@", arguments[@"title"]];
    NSString *body = [NSString stringWithFormat: @"%@", arguments[@"body"]];
    
    if (!tag || !alarm_id || !date || !title || !body || !hour || !minute) {
        result([FlutterError errorWithCode:@"INVALID_ARGUMENTS" message:@"缺少必要参数" details:nil]);
        return;
    }
    
    // 保存闹钟信息
    [[DBManager sharedManager] insertData:arguments completion:^(BOOL success, NSString * _Nullable msg) {
        
        if(success){
            
            // 创建通知内容
            if (@available(iOS 10.0, *)) {
                UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
                content.title = title;
                content.body = body;
                // 设置自定义铃声（若存在）
                content.sound = [self alarmSoundForCurrentBundle];
                content.userInfo = @{@"alarm_id": alarm_id, @"tag":tag};
                
                // 创建触发器
                NSArray *dateArr = [date componentsSeparatedByString:@"-"];
                NSDateComponents *triggerComponents = [[NSDateComponents alloc] init];

                if(dateArr.count == 3){
                    [triggerComponents setYear:[[dateArr firstObject] integerValue]];
                    [triggerComponents setMonth:[[dateArr objectAtIndex:1] integerValue]];
                    [triggerComponents setDay:[[dateArr lastObject] integerValue]];
                }
                
                [triggerComponents setHour:[hour integerValue]];
                [triggerComponents setMinute:[minute integerValue]];
                
                
                UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger
                                                          triggerWithDateMatchingComponents:triggerComponents
                                                          repeats:NO];
                
                // 创建通知请求
                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:[NSString stringWithFormat:@"%@&#&#&%@", tag, alarm_id]
                                                                                      content:content
                                                                                      trigger:trigger];
                
                // 添加通知
                UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (error) {
                            result(@{@"status":@(0), @"msg":[FlutterError errorWithCode:@"SET_REPEATING_ALARM_ERROR"
                                                        message:[NSString stringWithFormat:@"设置闹钟失败: %@", error.localizedDescription]
                                                                               details:nil]});
                        } else {
                            result(@{@"status":@(1), @"msg":msg});

                        }
                    });
                }];
                
            }
                        
        }else {
            result(@{@"status":@(0), @"msg":msg});
        }
   
    }];
        
    
}

- (void)setRepeatingAlarm:(NSDictionary*)arguments result:(FlutterResult)result {
    
    NSString *tag = [NSString stringWithFormat: @"%@", arguments[@"tag"]];
    NSString *alarm_id = [NSString stringWithFormat: @"%@", arguments[@"alarm_id"]];
    NSNumber *hour = arguments[@"hour"];
    NSNumber *minute = arguments[@"minute"];
    NSString *title = [NSString stringWithFormat: @"%@", arguments[@"title"]];
    NSString *body = [NSString stringWithFormat: @"%@", arguments[@"body"]];
    NSString *repeating = [NSString stringWithFormat: @"%@", arguments[@"repeating"]];
    
    if (!tag || !alarm_id || !hour || !minute || !title || !body) {
        result([FlutterError errorWithCode:@"INVALID_ARGUMENTS" message:@"缺少必要参数" details:nil]);
        return;
    }
    
    // 保存闹钟信息
    [[DBManager sharedManager] insertData:arguments completion:^(BOOL success, NSString * _Nullable msg) {
        
        if(success){
            
            // 创建通知内容
            if (@available(iOS 10.0, *)) {
                UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
                content.title = title;
                content.body = body;
                // 设置自定义铃声（若存在）
                content.sound = [self alarmSoundForCurrentBundle];
                content.userInfo = @{@"alarm_id": alarm_id, @"tag":tag ,@"isRepeating":repeating};
                
                // 创建每日重复触发器
                NSDateComponents *triggerComponents = [[NSDateComponents alloc] init];
                [triggerComponents setHour:[hour integerValue]];
                [triggerComponents setMinute:[minute integerValue]];
                
                UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger
                                                          triggerWithDateMatchingComponents:triggerComponents
                                                          repeats:[repeating isEqualToString :@"1"] ? YES:NO];
                
                // 创建通知请求
                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:[NSString stringWithFormat:@"%@&#&#&%@", tag, alarm_id]
                                                                                      content:content
                                                                                      trigger:trigger];
                
                // 添加通知
                UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (error) {
                            result(@{@"status":@(0), @"msg":[FlutterError errorWithCode:@"SET_REPEATING_ALARM_ERROR"
                                                        message:[NSString stringWithFormat:@"设置闹钟失败: %@", error.localizedDescription]
                                                                               details:nil]});
                        } else {
                            result(@{@"status":@(1), @"msg":msg});

                        }
                    });
                }];
                
            }
                        
        }else {
            
            result(@{@"status":@(0), @"msg":msg});
            
        }
        
        
    }];
    
  
    
}


// 根据alarm_id和tag取消闹钟.
- (void)cancelAlarm:(NSDictionary*)arguments result:(FlutterResult)result {
    NSString *alarm_id = arguments[@"alarm_id"];
    NSString *tag = arguments[@"tag"];
    
    // 从存储中移除
    [[DBManager sharedManager] deleteDataTag:tag withAlarmId:alarm_id completion:^(BOOL success, NSString * _Nullable msg) {
        
        if(success){
            // 取消通知
            if (@available(iOS 10.0, *)) {
                UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                [center removePendingNotificationRequestsWithIdentifiers:@[[NSString stringWithFormat:@"%@&#&#&%@", tag, alarm_id]]];
            } else {
                // Fallback on earlier versions
            }
            
            result(@{@"status":@(1), @"msg":msg});
        }else {
            result(@{@"status":@(0), @"msg":msg});
        }
                
    }];
    
}


// 根据tag取消闹钟.
- (void)cancelAlarmsByTag:(NSDictionary*)arguments result:(FlutterResult)result {

    NSString *tag = arguments[@"tag"];
    
    // 从存储中移除
    [[DBManager sharedManager] deleteDataTag:tag withAlarmId:@"" completion:^(BOOL success, NSString * _Nullable msg) {
        
        if(success){
            // 取消通知
            if (@available(iOS 10.0, *)) {
                
                NSMutableArray *identifiers = [NSMutableArray array];
                
                UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                
                [center getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
                    // 查出所有通知identifier
                    for (UNNotificationRequest * t in requests) {
                        NSArray *arr = [t.identifier componentsSeparatedByString:@"&#&#&"];
                        if([[arr firstObject] isEqualToString:tag]){
                            [identifiers addObject:t.identifier];
                        }
                        
                    };
                                    
                    [center removePendingNotificationRequestsWithIdentifiers:identifiers];
                    result(@{@"status":@(1), @"msg":msg});
                                    
                }];
       
            }
            
        }else {
            result(@{@"status":@(0), @"msg":msg});
        }
                
    }];
    
}

// 取消所以闹钟.
- (void)cancelAllAlarms:(NSDictionary*)arguments result:(FlutterResult)result {
    
    // 从存储中移除
    [[DBManager sharedManager] deleteDataTag:@"" withAlarmId:@"" completion:^(BOOL success, NSString * _Nullable msg) {
        
        if(success){
            // 取消通知
            if (@available(iOS 10.0, *)) {
                
                UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                // 取消所有通知
                [center removeAllPendingNotificationRequests];
                result(@{@"status":@(1), @"msg":msg});
       
            }
            
        }else {
            result(@{@"status":@(0), @"msg":msg});
        }
                
    }];
    
}


// 获取所有闹钟
- (void)getAllAlarms:(NSDictionary*)arguments result:(FlutterResult)result {
    
    [[DBManager sharedManager] queryDataTag:@"" withAlarmId:@"" completion:^(BOOL success, NSArray * _Nonnull resultArr, NSString * _Nullable msg) {
        if(success){
            result(@{@"status":@(1), @"data": resultArr, @"msg":msg});
        }else{
            result(@{@"status":@(0), @"data": @[], @"msg":msg});
        }
    }];

}

// 根据tag获取闹钟
- (void)getAlarmsByTag:(NSDictionary*)arguments result:(FlutterResult)result {
    NSString *tag = arguments[@"tag"];
    
    [[DBManager sharedManager] queryDataTag:tag withAlarmId:@"" completion:^(BOOL success, NSArray * _Nonnull resultArr, NSString * _Nullable msg) {
        if(success){
            result(@{@"status":@(1), @"data": resultArr, @"msg":msg});
        }else{
            result(@{@"status":@(0), @"data": @[], @"msg":msg});
        }
    }];

}

// 根据alarm_id和tag获取闹钟.
- (void)getAlarmByalarmId:(NSDictionary*)arguments result:(FlutterResult)result {
    
    NSString *alarm_id = arguments[@"alarm_id"];
    NSString *tag = arguments[@"tag"];
    
    [[DBManager sharedManager] queryDataTag:tag withAlarmId:alarm_id completion:^(BOOL success, NSArray * _Nonnull resultArr, NSString * _Nullable msg) {
        
        if(resultArr.count > 0){
            result(@{@"status":@(1), @"data": [resultArr firstObject], @"msg":msg});
        }else {
            result(@{@"status":@(1), @"msg":msg});

        }
    }];

}


#pragma mark - UNUserNotificationCenterDelegate

- (void)userNotificationCenter:(UNUserNotificationCenter *)center 
       willPresentNotification:(UNNotification *)notification 
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    // 前台显示通知
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center 
 didReceiveNotificationResponse:(UNNotificationResponse *)response 
         withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    // 处理通知点击
    NSString *alarm_id = response.notification.request.content.userInfo[@"alarm_id"];
    NSLog(@"用户点击了闹钟通知: %@", alarm_id);
    
    completionHandler();
}

@end
